package com.common.app.utls.network

import com.common.base.app.extras.no
import com.common.base.app.extras.yes
import okhttp3.Interceptor
import okhttp3.Response
import okio.Buffer
import okio.GzipSource
import java.nio.charset.Charset
import java.nio.charset.StandardCharsets

/**
 * 作者：sosou
 * <p>
 * 版本：1.0
 * <p>
 * 创建日期：2022/8/19
 * <p>
 * 描述：封装服务器返回值数据拦截判断
 * <p>
 * 修订历史：
 */
abstract class ResInterceptor : Interceptor {

    override fun intercept(chain: Interceptor.Chain): Response {
        val request = chain.request()
        val url = request.url.toString()
        val response = chain.proceed(request)

        // 检查请求是否有特定的header
        val skip = request.header("Skip-Interceptor") == "true"

        skip.no {
            response.body?.let { responseBody ->
                val contentLength = responseBody.contentLength()
                val source = responseBody.source()
                source.request(Long.MAX_VALUE)
                var buffer = source.buffer

                if ("gzip".equals(response.headers["Content-Encoding"], ignoreCase = true)) {
                    GzipSource(buffer.clone()).use { gzippedResponseBody ->
                        buffer = Buffer()
                        buffer.writeAll(gzippedResponseBody)
                    }
                }

                val contentType = responseBody.contentType()
                val charset: Charset =
                    contentType?.charset(StandardCharsets.UTF_8) ?: StandardCharsets.UTF_8
                if (contentLength != 0L) {
                    return intercept(response, url, buffer.clone().readString(charset))
                }
            }
        }
        return response
    }

    abstract fun intercept(response: Response, url: String, body: String): Response
}